package com.aabte.weather.wearthercollection.weather;

import com.aabte.weather.wearthercollection.city.City;
import com.aabte.weather.wearthercollection.city.CityDataService;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WeatherDataSyncJob extends QuartzJobBean {

    @Resource
    private CityDataService cityDataService;

    @Resource
    private WeatherDataCollectionService weatherDataCollectionService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        log.info("start sync weather data.");
        List<City> cities;
        try {
            cities = cityDataService.listCity();
        } catch (Exception e) {
            log.warn("get city list failed.", e);
            return;
        }

        for (City city : cities) {
            String cityId = city.getCityId();
            log.info("syncing weather data. cityId: {}", cityId);
            weatherDataCollectionService.syncDataByCityId(cityId);
        }
        log.info("end sync weather data.");
    }

    private boolean flag = true;

    @EventListener(value = ContextRefreshedEvent.class)
    public void setup() {
        if (flag) {
            flag = false;
            final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    1, 1, 1L, TimeUnit.SECONDS,
                    new SynchronousQueue<>(), new DefaultThreadFactory("weather-data-init-thread"));
            threadPoolExecutor.execute(() -> this.executeInternal(null));
            threadPoolExecutor.shutdown();
        }
    }
}
